package com.wing.sell.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.service.ProductTypeService;
import com.wing.product.service.ProductUnitService;
import com.wing.res.model.entity.ReceiptRecord;
import com.wing.res.model.entity.ReceiptRecordDetail;
import com.wing.res.service.ReceiptRecordDetailService;
import com.wing.res.service.ReceiptRecordService;
import com.wing.sell.dao.DeliveryPlanDao;
import com.wing.sell.dao.FinishedOrderDetailDao;
import com.wing.sell.model.entity.DeliveryRecord;
import com.wing.sell.model.entity.DeliveryRecordDetail;
import com.wing.sell.model.entity.FinishedOrderDetail;
import com.wing.sell.model.request.DeliveryRecordForm;
import com.wing.sell.model.response.FinishedOrderDetailExcelVo;
import com.wing.sell.model.response.FinishedOrderDetailVo;
import com.wing.sell.model.response.OrderSkuDetailSearchVo;
import com.wing.sell.service.DeliveryRecordDetailService;
import com.wing.sell.service.DeliveryRecordService;
import com.wing.sell.service.FinishedOrderDetailService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 销售订单表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class FinishedOrderDetailServiceImpl extends ServiceImpl<FinishedOrderDetailDao, FinishedOrderDetail> implements FinishedOrderDetailService{

    @Autowired
    private ProductUnitService productUnitService;

    @Autowired
    private ProductTypeService productTypeService;

    @Autowired
    private DeliveryPlanDao deliveryPlanDao;

    @Autowired
    private DeliveryRecordService deliveryRecordService;

    @Autowired
    private FinishedOrderDetailService finishedOrderDetailService;

    @Autowired
    private ReceiptRecordService receiptRecordService;

    @Autowired
    private ReceiptRecordDetailService receiptRecordDetailService;

    @Autowired
    private DeliveryRecordDetailService deliveryRecordDetailService;

    /**
     * 查询成品销售sku信息
     * @param orderId 订单id
     * @param warehouseId 仓库id
     * @return
     */
    @Override
    public List<OrderSkuDetailSearchVo> listByInfo(Long orderId, Long warehouseId) {
        List<OrderSkuDetailSearchVo> searchVos = baseMapper.listByInfo(orderId, warehouseId);

        //查询所有的单位
        List<ProductUnitInfo> infoList = productUnitService.list();

        //查询所有的类型信息
        List<ProductType> list = productTypeService.listAndSelectBaseUnit();

        searchVos.forEach(vo -> {
            for (ProductUnitInfo productUnitInfo : infoList) {
                if (productUnitInfo.getId().equals(vo.getMainUnitId())) {
                    vo.setMainUnitName(productUnitInfo.getName());
                }
            }

            for (ProductType productType : list) {
                if (productType.getId().equals(vo.getProductTypeId())) {
                    vo.setProductTypeName(productType.getName());
                    vo.setBaseUnitId(productType.getBaseUnitId());
                    vo.setBaseUnitName(productType.getBaseUnitName());
                }
            }
        });
        //查询 成品订单 的数据
        QueryWrapper<FinishedOrderDetail> details = new QueryWrapper<>();
        details.eq("finished_id", orderId);
        details.eq("is_deleted", false);
        List<FinishedOrderDetail> finishedOrderDetails = this.finishedOrderDetailService.list(details);
        if (CollectionUtil.isNotEmpty(finishedOrderDetails)) {
            for (FinishedOrderDetail finishedOrderDetail : finishedOrderDetails) {
                if (finishedOrderDetail.getProductDetailId()!=null){
                    for (OrderSkuDetailSearchVo searchVo : searchVos) {
                        if (finishedOrderDetail.getProductDetailId().equals(searchVo.getProductDetailId())) {
                            searchVo.setCurrentCostPrice(finishedOrderDetail.getPrice());
                        }
                    }
                }
            }
        }
        return searchVos;
    }


    /**
     * 成品订单生成交付记录2
     * @param deliveryRecordForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer generateOrderResult(DeliveryRecordForm deliveryRecordForm) {
        //校验   库存校验逻辑


        List<DeliveryRecordDetail> deliveryRecordDetails = deliveryRecordForm.getDeliveryRecordDetails();
        if(deliveryRecordDetails.size()<=0){
            return 0;
        }

        List<OrderSkuDetailSearchVo> searchVos = baseMapper.listByInfoIds(deliveryRecordForm.getSaleOrderId(), deliveryRecordForm.getWarehouseId());

        for (DeliveryRecordDetail deliveryRecordDetail : deliveryRecordDetails) {

            for (OrderSkuDetailSearchVo searchVo : searchVos) {

                if(deliveryRecordDetail.getProductDetailId().equals(searchVo.getProductDetailId()) && deliveryRecordDetail.getSkuCode().equals(searchVo.getSkuCode())){
                  // 假设 getShipmentQty() 返回 Long 类型, getHaveQuantity() 返回 BigDecimal 类型
                    Long shipmentQtyLong = deliveryRecordDetail.getShipmentQty();
                    BigDecimal quantity = searchVo.getHaveQuantity();
                    if (shipmentQtyLong != null && quantity != null) {
                        // 将 Long 转换为 BigDecimal
                        BigDecimal shipmentQty = new BigDecimal(shipmentQtyLong);
                        // 使用 compareTo 方法进行比较
                        if (shipmentQty.compareTo(quantity) > 0) {
                            return 0;
                        }
                    }
               }

            }

        }

        DeliveryRecord deliveryRecord = new DeliveryRecord();
        //交付记录编号
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        //getDayMaxNo
        String today = format.format(new Date());
        Integer maxCode = deliveryPlanDao.getDayMaxNo("sel_delivery_record");
        String maxNo = CodeUtil.getCode(maxCode);
        String code = today + maxNo;
        CopyOptions copyOptions = CopyOptions.create().setEditable(DeliveryRecord.class).setIgnoreError(true).setIgnoreNullValue(true);
        BeanUtil.copyProperties(deliveryRecordForm, deliveryRecord, copyOptions);
        deliveryRecord.setRecordCode(code);
        deliveryRecord.setNo(Integer.valueOf(maxNo));
        deliveryRecord.setDay(Integer.valueOf(today));
        deliveryRecord.setSaleOrderCode(deliveryRecordForm.getSaleOrderCode());
        boolean save = deliveryRecordService.save(deliveryRecord);
        if (!save) {
            return 0;
        }
        //交付记录id
        ReceiptRecord receiptRecord = ReceiptRecord.builder()
                .auditPerson(JwtUtils.getLoginUserId())
                .auditPersonName(JwtUtils.getLoginUsername())
                //出库已审核
                .auditResult("2")
                .creator(JwtUtils.getLoginUserId())
                .createTime(new Date())
                .creatorName(JwtUtils.getLoginUsername())
                .inventoryTypeId(deliveryRecordForm.getTypeId())
                //放入交付记录id
                .workOrderId(deliveryRecord.getId())
                .warehouseType(deliveryRecordForm.getWarehouseTypeId())
                .receiptWarehouse(deliveryRecordForm.getWarehouseId())
                .build();
        String taskNo = UniqueIdGeneratorUtil.generateUniqueId("LL", "yyyyMMdd", 1000, 9999);
        receiptRecord.setCode(taskNo);
        //待审核
        receiptRecord.setStatus(2);
        receiptRecord.setRemark("成品发货物流记录自动生成");
        this.receiptRecordService.save(receiptRecord);
        //成品销售逻辑
        if (CollectionUtil.isNotEmpty(deliveryRecordForm.getDeliveryRecordDetails())) {
            //交付记录列表
            List<DeliveryRecordDetail> recordDetailList = new ArrayList<>();
            //批量修改的库存列表
            List<FinishedOrderDetail> updateOrderDetail = new ArrayList<>();
            //仓库物料相关列表
            List<ReceiptRecordDetail> receiptRecordDetails = new ArrayList<>();

            for (DeliveryRecordDetail deliveryRecordDetail : deliveryRecordForm.getDeliveryRecordDetails()) {
                deliveryRecordDetail.setSkuId(deliveryRecordDetail.getProductDetailId());
                deliveryRecordDetail.setUnitId(deliveryRecordDetail.getMainUnitId());
                deliveryRecordDetail.setUnitName(deliveryRecordDetail.getMainUnitName());
                deliveryRecordDetail.setProductName(deliveryRecordDetail.getSkuName());
                deliveryRecordDetail.setSubtotalAmount(deliveryRecordDetail.getSubtotalAmount());
                Long selRemainQuality = deliveryRecordDetail.getSelRemainQuality();
                //上次剩余
                Long lastQuality = null;
                if (null != selRemainQuality && !selRemainQuality.equals(0L)) {
                    //得到此次剩余
                    lastQuality = selRemainQuality - deliveryRecordDetail.getShipmentQty();
                    deliveryRecordDetail.setSurplus(lastQuality);
                }
                deliveryRecordDetail.setDeliveryRecordId(deliveryRecord.getId());
                //交付情况:0-未交付，1-交付有剩余，2-交付完成
                if (null != lastQuality && lastQuality > 0L) {
                    deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.JFYSY.getCode());
                } else if (null != lastQuality && lastQuality == 0L) {
                    deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.JFWC.getCode());
                } else {
                    deliveryRecordDetail.setDeliverySituation(ProductEnum.deliverySituationEmum.WJF.getCode());
                }
                //保存记录
                recordDetailList.add(deliveryRecordDetail);
                //修改对应订单状态 以及剩余库存
                QueryWrapper<FinishedOrderDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("id", deliveryRecordDetail.getOrderDetailId());
                queryWrapper.eq("finished_id", deliveryRecord.getSaleOrderId());
                FinishedOrderDetail one = this.getOne(queryWrapper);
                one.setSelRemainQuality(lastQuality);
                one.setUpdateTime(LocalDateTime.now());
                one.setModifier(JwtUtils.getLoginUserId());
                one.setModifierName(JwtUtils.getLoginUsername());
                updateOrderDetail.add(one);

                ReceiptRecordDetail receiptRecordDetail = new ReceiptRecordDetail();
                receiptRecordDetail.setReceiptRecordId(receiptRecord.getId());
                receiptRecordDetail.setProductDetailId(deliveryRecordDetail.getProductDetailId());
                receiptRecordDetail.setReceiptNum(new BigDecimal(deliveryRecordDetail.getShipmentQty()));
                receiptRecordDetail.setRemark("成品发货物流记录自动生成");
                receiptRecordDetail.setCreateTime(new Date());
                receiptRecordDetails.add(receiptRecordDetail);
            }
            //批量修改
            this.deliveryRecordDetailService.saveBatch(recordDetailList);
            this.receiptRecordDetailService.saveBatch(receiptRecordDetails);
            this.updateBatchById(updateOrderDetail);
            return 1;
        }
        return 0;
    }

    /**
     * 查询成品订单产品信息
     * @param orderId
     * @return
     */
    @Override
    public List<OrderSkuDetailSearchVo>    listByInfoBy(Long orderId) {

        List<OrderSkuDetailSearchVo> searchVos = this.baseMapper.listByInfoBy(orderId);

        //查询所有的单位
        List<ProductUnitInfo> infoList = productUnitService.list();

        //查询所有的类型信息
        List<ProductType> list = productTypeService.listAndSelectBaseUnit();

        searchVos.forEach(vo -> {
            for (ProductUnitInfo productUnitInfo : infoList) {
                if (productUnitInfo.getId().equals(vo.getMainUnitId())) {
                    vo.setMainUnitName(productUnitInfo.getName());
                }
            }

            for (ProductType productType : list) {
                if (productType.getId().equals(vo.getProductTypeId())) {
                    vo.setProductTypeName(productType.getName());
                    vo.setBaseUnitId(productType.getBaseUnitId());
                    vo.setBaseUnitName(productType.getBaseUnitName());
                }
            }
        });
        //查询 成品订单 的数据
        QueryWrapper<FinishedOrderDetail> details = new QueryWrapper<>();
        details.eq("finished_id", orderId);
        details.eq("is_deleted", false);
        List<FinishedOrderDetail> finishedOrderDetails = this.finishedOrderDetailService.list(details);
        if (CollectionUtil.isNotEmpty(finishedOrderDetails)) {
            for (FinishedOrderDetail finishedOrderDetail : finishedOrderDetails) {
                if (finishedOrderDetail.getProductDetailId()!=null){
                    for (OrderSkuDetailSearchVo searchVo : searchVos) {
                        if (finishedOrderDetail.getProductDetailId().equals(searchVo.getProductDetailId())) {
                            searchVo.setCurrentCostPrice(finishedOrderDetail.getPrice());
                        }
                    }
                }
            }
        }

        return searchVos;
    }

    /**
     * 查询成品销售明细
     * @param pg
     * @param params
     * @return
     */
    @Override
    public Page<FinishedOrderDetailVo> pageList4app(Page<FinishedOrderDetailVo> pg, Map<String, Object> params) {
        List<FinishedOrderDetailVo> list = baseMapper.pageList4app(pg, params);
        pg.setRecords(list);
        return pg;
    }

    @Override
    public List<FinishedOrderDetailExcelVo> exportInProductInfoDetail(Map<String, Object> params) {
        return baseMapper.exportInProductInfoDetail(params);
    }
}
